package git.soulbgm.service.task;

import git.soulbgm.pojo.MonitoringServiceInfo;
import git.soulbgm.service.MonitoringServiceInfoService;
import git.soulbgm.utils.DateUtil;
import git.soulbgm.utils.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ScheduledFuture;

/**
 * @author SoulBGM
 * @version 1.0
 * @date 2019/7/8 15:46
 */
@Slf4j
@Component
public class MonitoringScheduleTask {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @Autowired
    private MonitoringServiceInfoService service;

    @Scheduled(cron = "0/5 * * * * ?")
    public void test() {
        List<MonitoringServiceInfo> list = service.findAll();
        for (MonitoringServiceInfo info : list) {
            Long id = info.getId();
            Integer frequency = info.getFrequency();
            if (!TaskMap.containsTask(id)) {
                ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(() -> {
                    String result = OkHttpUtil.get(info.getMonitorUrl());
                    if (result == null) {
                        log.error("监控{}地址响应失败, 时间{}", info.getMonitorUrl(), DateUtil.getNowStr());
                    } else {
                        log.info("监控{}地址响应成功，时间{}", info.getMonitorUrl(), DateUtil.getNowStr());
                    }
                }, triggerContext -> {
                    Calendar now = DateUtil.getCalendar();
                    DateUtil.offsetDate(now, DateUtil.SECOND, frequency);
                    return now.getTime();
                });
                TaskMap.add(id, future);
            }
        }
        updateTask(list);
    }

    private void updateTask(List<MonitoringServiceInfo> list) {
        Set<Long> longs = TaskMap.keySet();
        List<Long> delTask = new ArrayList<>();
        for (Long id : longs) {
            boolean flag = false;
            for (MonitoringServiceInfo info : list) {
                if (info.getId().equals(id)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                delTask.add(id);
            }
        }
        for (Long id : delTask) {
            ScheduledFuture future = TaskMap.get(id);
            if (future != null) {
                future.cancel(true);
            }
            TaskMap.remove(id);
        }
    }

}
